// 
//  JKAudioTool.m
//  02-播放音效
// 
//  Created by albert on 16/4/7.
//  Copyright (c) 2016年 albert. All rights reserved.
// 

#import "JKAudioTool.h"

static NSMutableDictionary *_soundIDs;
static NSMutableDictionary *_players;

@implementation JKAudioTool

+ (void)initialize{
    if (_soundIDs == nil) {
        _soundIDs = [NSMutableDictionary dictionary];
    }
    
    if (_players == nil) {
        _players = [NSMutableDictionary dictionary];
    }
}

#pragma mark - 播放音乐
/** 仅返回对应的播放器 */
+ (AVAudioPlayer *)playerWithMusicName:(NSString *)musicName{
    
    // 如果传来的参数为空，直接崩
    assert(musicName);
    
    // 1、定义播放器
    AVAudioPlayer *player = nil;
    // 2、从字典中取出播放器，如果取出来为空，则创建对应的播放器
    player = _players[musicName];
    if (player == nil) {
        // 2.1 获取对应音乐资源
        NSURL *url = [[NSBundle mainBundle] URLForResource:musicName withExtension:nil];
        
        if (url == nil) return nil;
        
        NSError *error = nil;
        
        // 2.2 创建对应的播放器
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
        
        // 2.3 将player存入字典中
        [_players setValue:player forKey:musicName];
        
        // 2.4 准备播放
        [player prepareToPlay];
    }
    
    return player;
}

/** 播放音乐 */
+ (void)playMusicWithMusicName:(NSString *)musicName{
    
    [[self playerWithMusicName:musicName] play];
}

/** 暂停音乐 */
+ (void)pauseMusicWithMusicName:(NSString *)musicName{
    assert(musicName);
    
    // 1、取出对应的播放器
    AVAudioPlayer *player = _players[musicName];
    
    // 2、判断player是否为nil，
    if (player) {
        [player pause];
    }
}

/** 停止音乐 */
+ (void)stopMusicWithMusicName:(NSString *)musicName{
    assert(musicName);
    
    // 1、取出对应的播放器
    AVAudioPlayer *player = _players[musicName];
    
    // 2、判断player是否为nil，
    if (player) {
        [player stop];
        // 从字典中移除
        [_players removeObjectForKey:musicName];
        // 清空
        player = nil;
    }
}

#pragma mark - 播放音效
/** 播放音效 */
+ (void)playSoundWithSoundName:(NSString *)soundName{
    
    // 如果传来的参数为空，直接崩
    assert(soundName);
    
    // 1、定义systemSoundID，根据音效文件来生成
    SystemSoundID soundID = 0;
    
    // 2、从字典中取出对应的soundID，如果是0，表示之前没有存放在字典
    soundID = [_soundIDs[soundName] unsignedIntValue];
    if (soundID == 0) {
        // 根据音效文件，来生成systemSoundID
        NSURL *url = [[NSBundle mainBundle] URLForResource:soundName withExtension:nil];
        // 转成C语言的url
        CFURLRef urlRef  = (__bridge CFURLRef)(url);
        
        if (urlRef == NULL) return;
        
        AudioServicesCreateSystemSoundID(urlRef, &soundID);
        
        // 将soundID存入字典
        [_soundIDs setValue:@(soundID) forKey:soundName];
    }
    
    // 3、播放音效
    AudioServicesPlaySystemSound(soundID);
}
@end
